//
//  Preorder.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/14.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import Foundation

struct Preorder: Codable {
    
    static let status = [1: "待支付",  //支付
                         2: "待分配车辆",    //1
                         3: "调度中",    //2
                         4: "调度中",      //2
                         5: "预约完成",     //3\4
                         6: "退款中",      //6
                         7: "已退款",      //6
                         8: "预约取消"]     //5
    
    struct Config: Codable {
        
        /// 用车开始时间
        let useStartTime: Int
        
        /// 用车结束时间
        let useEndTime: Int
        
        /// 车型ID
        let carTypeId: String
        
        /// 车型名称
        let carTypeName: String
        
        let parkingCarData: [ParkingCarData]
        
        enum CodingKeys : String, CodingKey {
            case useStartTime = "use_start_time"
            case useEndTime = "use_end_time"
            case carTypeId = "car_type_id"
            case carTypeName = "car_type_name"
            case parkingCarData = "parking_car_data"
        }
        
        struct ParkingCarData: Codable {
            
            /// 停车范围ID
            let parkingCarId: String
            
            /// 停车距离
            let parkingDistance: Int
            
            /// 预约金额
            let preAmount: String
            
            enum CodingKeys : String, CodingKey {
                case parkingCarId = "parking_car_id"
                case parkingDistance = "parking_distance"
                case preAmount = "pre_amount"
            }
        }
    }
    
    struct Create: Codable {
        
        /// 预约订单ID
        let preorderId: String
        
        /// 下单时间
        let createdTime: Int
        
        /// 余额是否可用标识（0：否；1：是）
        let balanceFlag: Int
        
        /// 预约金额
        let preorderAmount: String
        
        enum CodingKeys : String, CodingKey {
            case preorderId = "preorder_id"
            case createdTime = "created_time"
            case balanceFlag = "balance_flag"
            case preorderAmount = "preorder_amount"
        }
        
        init(preorderId: String, createdTime: Int, balanceFlag: Int, preorderAmount: String) {
            self.preorderId = preorderId
            self.createdTime = createdTime
            self.balanceFlag = balanceFlag
            self.preorderAmount = preorderAmount
        }
    }
    
    struct List: Codable {
        
        struct Item: Codable {
            
            /// 预约订单ID
            let preorderId: String
            
            /// 预约订单号
            let preorderSn: String
            
            /// 车型名称
            let carTypeName: String
            
            /// 用车时间
            let useCarTime: Int
            
            /// 用车地址
            let useCarAddress: String
            
            /// 预约单状态
            let preorderStatus: Int
            
            /// 下单时间
            let createdTime: Int
            
            /// 预约费用
            let preorderAmount: String
            
            /// 余额是否可用标识（0：否；1：是）
            let balanceFlag: Int
            
            enum CodingKeys : String, CodingKey {
                case preorderId = "preorder_id"
                case preorderSn = "preorder_sn"
                case carTypeName = "car_type_name"
                case useCarTime = "use_car_time"
                case useCarAddress = "use_car_address"
                case preorderStatus = "preorder_status"
                case createdTime = "created_time"
                case preorderAmount = "preorder_amount"
                case balanceFlag = "balance_flag"
            }
        }
        
        let list: [Item]
        
        /// 总条数（1:待支付;2:待分配车辆;3:待调度人员;4:调度中;5:预约完成6:退款中;7:已退款;8:预约取消）
        let total: Int
        
        /// 页数
        let page: String
        
        enum CodingKeys : String, CodingKey {
            case total = "total"
            case page = "page"
            case list = "list"
        }
    }
    
    struct Pay: Codable {
        
        /// 订单ID
        let preorderId: String
        
        /// 支付数据
        let payStr: String
        
        /// 支付状态（1：未支付；2：已支付）
        let payStatus: Int
        
        enum CodingKeys : String, CodingKey {
            case preorderId = "preorder_id"
            case payStr = "pay_str"
            case payStatus = "pay_status"
        }
    }
    
    struct Detail: Codable {
        
        /// 预约订单ID
        let preorderId: String
        
        /// 订单号
        let preorderSn: String
        
        /// 车型
        let carTypeName: String
        
        /// 用车地址
        let useCarAddress: String
        
        /// 用车时间
        let useCarTime: Int
        
        /// 订单状态（1:待支付;2:待分配车辆;3:待调度人员;4:调度中;5:预约完成6:退款中;7:已退款;8:预约取消）
        let status: Int
        
        /// 车牌号
        let plateNumber: String
        
        /// 停车地址
        let parkingAddress: String
        
        /// 预约费用
        let preAmount: String
        
        /// 是否可以取消(0:否；1：是)
        let isCancel: Int
        
        /// 已退款预约费用
        let preRefundAmount: String
        
        enum CodingKeys : String, CodingKey {
            case preorderId = "preorder_id"
            case preorderSn = "preorder_sn"
            case carTypeName = "car_type_name"
            case useCarAddress = "use_car_address"
            case useCarTime = "use_car_time"
            case status = "status"
            case plateNumber = "plate_number"
            case parkingAddress = "parking_address"
            case preAmount = "pre_amount"
            case isCancel = "is_cancel"
            case preRefundAmount = "pre_refund_amount"
        }
    }
    
    struct CancelReason: Codable {
        struct Item: Codable {
            let preorderCancelReasonId: String
            let reasonName: String
            
            enum CodingKeys : String, CodingKey {
                case preorderCancelReasonId = "preorder_cancel_reason_id"
                case reasonName = "reason_name"
            }
        }
        
        let preorderCancelReasonList: [Item]
        
        enum CodingKeys : String, CodingKey {
            case preorderCancelReasonList = "preorder_cancel_reason_list"
        }
    }
}

extension Preorder {
    
    /// 获取预约用车配置信息
    ///
    /// - Parameters:
    ///   - location: 经纬度
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func config(location: CLLocationCoordinate2D,
                     success: @escaping (Config?) -> (),
                     failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["lng": String(location.longitude),
                                         "lat": String(location.latitude)]
        
        Base<Config>.request(URIString: "user/query_preorder_config", parameters: parameters, success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    /// 预约下单
    ///
    /// - Parameters:
    ///   - useCarTime: 用车时间
    ///   - useCarAddress: 用车地址
    ///   - location: 用车经纬度
    ///   - parkingCarId: 停车范围ID
    ///   - isAcceptAdjust: 是否接受调剂（0：否；1：是）
    ///   - carTypeId: 车型ID
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func create(useCarTime: Int,
                       useCarAddress: String,
                       location: CLLocationCoordinate2D,
                       parkingCarId: String,
                       isAcceptAdjust: Int,
                       carTypeId: String,
                       success: @escaping (Create?) -> (),
                       failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = [
            "use_car_time": useCarTime,
            "use_car_address": useCarAddress,
            "use_car_lng": String(location.longitude),
            "use_car_lat": String(location.latitude),
            "parking_car_id": parkingCarId,
            "is_accept_adjust": isAcceptAdjust,
            "car_type_id": carTypeId]
        
        Base<Create>.request(URIString: "user/create_preorder", parameters: parameters, success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    /// 取消预约
    ///
    /// - Parameters:
    ///   - preorderId: 预约订单ID
    ///   - reason: 取消原因
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func cancel(preorderId: String,
                       reason: String,
                       success: @escaping () -> (),
                       failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = [
            "preorder_id": preorderId,
            "reason": reason]
        
        Base<String>.request(URIString: "user/cancel_appoint", parameters: parameters, success: { data in
            success()
        }) { error, data in
            failure(error)
        }
    }
    
    /// 预约订单列表
    ///
    /// - Parameters:
    ///   - page: 页数
    ///   - pageSize: 每页显示条数
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func list(page: Int,
                     pageSize: Int?,
                     success: @escaping (List?) -> (),
                     failure: @escaping (Message) -> ()) {
        
        var parameters: [String: Any] = ["page": page]
        
        if let size = pageSize {
            parameters["page_size"] = size
        }
        
        Base<List>.request(URIString: "user/query_preorder_list", parameters: parameters, success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    /// 预约订单支付
    ///
    /// - Parameters:
    ///   - preorderId: 订单iD
    ///   - payment: 支付方式（1：支付宝；2：微信；6：余额支付）
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func pay(preorderId: String,
                    payment: Order.Pay.Payment,
                    success: @escaping (Pay?) -> (),
                    failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["preorder_id": preorderId,
                                         "payment": payment.rawValue]
        
        Base<Pay>.request(URIString: "user/preorder_pay", parameters: parameters, success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    /// 预约订单详情
    ///
    /// - Parameters:
    ///   - preorderId: 预约订单ID
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func detail(preorderId: String,
                       success: @escaping (Detail?) -> (),
                       failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["preorder_id": preorderId]
        
        Base<Detail>.request(URIString: "user/query_preorder_detail", parameters: parameters, success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    
    /// 获取预约取消原因列表
    ///
    /// - Parameters:
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func cancelReason(success: @escaping ([CancelReason.Item]?) -> (),
                             failure: @escaping (Message) -> ()) {
        
        Base<CancelReason>.request(URIString: "user/get_preorder_cancel_reason", success: { data in
            success(data?.preorderCancelReasonList)
        }) { error, data in
            failure(error)
        }
    }
}
